using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using FlexWiki;
using FlexWiki.Formatting;
using FlexWiki.Web;
using AspNetForums.Components;

namespace AspNetForums.Wiki
{
	/// <summary>
	/// Summary description for ManageWikiFiles.
	/// </summary>
	public class ManageWikiFiles : System.Web.UI.Page
	{
		static readonly string fromPath = Globals.ApplicationPath + "/wiki/wikibases/channel9";
		static readonly string toPath = Globals.ApplicationPath + "/wiki_backup";
		
		private void Page_Load(object sender, System.EventArgs e)
		{
			Context.Server.ScriptTimeout = 440;
			CleanHouse();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion


		private void CleanHouse()
		{
			string toFolder = Server.MapPath( toPath );
			string fromFolder = Server.MapPath( fromPath );
		
			Federation TheFederation = new Federation( Server.MapPath("NamespaceMap.xml") );
			string ns = "Channel9";
			ContentBase cb = TheFederation.ContentBaseForNamespace(ns);
			int numFiles = 0;

			foreach( AbsoluteTopicName topic in cb.AllTopicsSortedLastModifiedDescending(true) )
			{
				int startAt = 2;
				int i = 0;
				foreach( TopicName tName in cb.AllVersionsForTopic(topic) )
				{
					string fileName = tName.Name + "(" + tName.Version + ").awiki";
					
					if( i > startAt )
					{
						if( !File.Exists( Path.Combine( toFolder, fileName )) )
						{
							File.Move( Path.Combine( fromFolder, fileName ), Path.Combine( toFolder, fileName ) );
						}
					}
					i++;
					numFiles++;
				}
			}
			
			if( this.FindControl("FinishedLabel") != null )
			{
				this.FindControl("FinishedLabel").Visible = true;
				((Label)this.FindControl("FinishedLabel")).Text = "<b>Finished archiving " + numFiles.ToString() + " files sucessfully.</b>";
			}
		}
	}
}
